<?php namespace App\Client\Stats;

use Input;
//基础条件
use App\Core\Repository\Criterias\FixedCriteria;
use App\Core\Repository\Criterias\BetweenCriteria;

use App\Admin\Orders\Orders\Meta;
use App\Admin\Orders\Orders\Repository;

trait Service {
    
    use \App\Core\Service\Service;
    
    protected function bootService(){
        $this->bootBaseService();
        $this->setRepository(new Repository);
        $this->setMeta(new Meta);
        $this->repository = $this->getRepository();
        ini_set('memory_limit', '3000M');
        set_time_limit(0);
    }
	
    //主页
    public function index(){
        $monthRaw = Input::get('month');
        if(!$monthRaw){
            $monthRaw = date('Y-m');
        }
        list($year, $month) = explode('-', $monthRaw);
        $monthName = $year.'年'.str_replace('0', '', $month).'月份';
        //统计区间
        $startTime = strtotime($year.'-'.$month.'-01');
        if(str_replace('0', '', $month) < 12){
            $endTime = strtotime($year.'-'.(intval($month) + 1).'-01');
        }else{
            $endTime = strtotime((intval($year) + 1).'-01-01');
        }
        //所有记录
        $records = $this->repository->resetQuery()->resetCriteria()->addCriterias([
            new BetweenCriteria('created_at', $startTime, $endTime, true, false),
            new FixedCriteria('status', '1'),
            new FixedCriteria('type', '1'),
            new Criterias\MatchClient()
        ])->all();
        $records->load('goods');
        $goodses = [];
        $userCount = 0;//用户量
        $userIds = [];
        $useTimes = 0;//总使用次数
        $useTime = 0;//总使用时长
        $amount = 0;//总费用
        $timesGroup = [];//商品使用次数对比
        $timeGroup = [];//商品使用时长对比
        $days = [];
        $timesDaily = [];
        $timeDaily = [];
        $endday = date('d', $endTime-3600);
        for($i = 1;$i<=$endday;$i++){
            //wyc-2018-7-24 修改
            if($i<10){
                $days[] = $year.'-'.$month.'-0'.$i;
                $timesDaily[$year.'-'.$month.'-0'.$i] = [];
                $timeDaily[$year.'-'.$month.'-0'.$i] = [];
            }else{
                $days[] = $year.'-'.$month.'-'.$i;
                $timesDaily[$year.'-'.$month.'-'.$i] = [];
                $timeDaily[$year.'-'.$month.'-'.$i] = [];
            }
           
        }
        foreach($records as $record){
            if(!isset($goodses['_'.$record->goods_id])){
                $goodses['_'.$record->goods_id] = $record->goods;
            }
            //用户量
            if(!in_array($record->user_id, $userIds)){
                $userIds[] = $record->user_id;
                $userCount++;
            }
            //总次数
            $useTimes ++;
            //总时长
            $time = 0;
            if($record->end_time && $record->start_time && $record->start_time < $record->end_time){
                $time = intval($record->end_time) - intval($record->start_time);
                $useTime += $time;
            }
            //总金额
            $amount += floatval($record->amount);
            //商品次数
            if(!isset($timesGroup['_'.$record->goods_id])){
                $timesGroup['_'.$record->goods_id] = 1;
            }else{
                $timesGroup['_'.$record->goods_id] += 1;
            }
            //商品时长
            if(!isset($timeGroup['_'.$record->goods_id])){
                $timeGroup['_'.$record->goods_id] = intval($time);
            }else{
                $timeGroup['_'.$record->goods_id] += intval($time);
            }
            //使用次数（每天）
            $theDay = $record->created_at->format('Y-m-d');
            if(isset($timesDaily[$theDay])){
                if(!isset($timesDaily[$theDay]['_'.$record->goods_id])){
                    $timesDaily[$theDay]['_'.$record->goods_id] = 1;
                }else{
                    $timesDaily[$theDay]['_'.$record->goods_id] += 1;
                }
            } 
            //使用时长（每天）
            //wyc-2018-7-24 修改
            $theDay = date('Y-m-d',$record->end_time);
            if(isset($timeDaily[$theDay])){
                if(!isset($timeDaily[$theDay]['_'.$record->goods_id])){
                    $timeDaily[$theDay]['_'.$record->goods_id] = intval(intval($time)/60);
                }else{
                    $timeDaily[$theDay]['_'.$record->goods_id] += intval(intval($time)/60);
                }
            }
        }
        $timesGroupData = [];
        foreach($timesGroup as $key => $item){
            if(isset($goodses[$key])){
                $timesGroupData[] = [
                    'value' => $item,
                    'name' => $goodses[$key]->name
                ];
            }
        }
        $timeGroupData = [];
        foreach($timeGroup as $key => $item){
            if(isset($goodses[$key])){
                $hours = $item ? intval(intval($item)/60) : 0;
                $timeGroupData[] = [
                    'value' => $hours,
                    'name' => $goodses[$key]->name
                ];
            }
        }
        $timesDailyData = [];
        $timesDailyGoodsNames = [];
        foreach($goodses as $goods){
            $timesDailyGoodsNames[] = $goods['name'];
            $item = [
                'name' => $goods['name'],
                'type' => 'line',
                'stack' => '总量',
                'data' => []
            ];
            foreach($timesDaily as $day => $items){
                $count = 0;
                foreach($items as $goodsId_ => $times) {
                    if('_'.$goods['id'] == $goodsId_){
                        $count = $times;
                    }
                }
                $item['data'][] = $count;
            }
            $timesDailyData[] = $item;
        }
        $timesDailyDays = array_keys($timesDaily);
        $timeDailyData = [];
        $timeDailyGoodsNames = [];
        foreach($goodses as $goods){
            $timeDailyGoodsNames[] = $goods['name'];
            $item = [
                'name' => $goods['name'],
                'type' => 'line',
                'stack' => '总量',
                'data' => []
            ];
            foreach($timeDaily as $day => $items){
                $count = 0;
                foreach($items as $goodsId_ => $time) {
                    if('_'.$goods['id'] == $goodsId_){
                        $count = $time;
                    }
                }
                $item['data'][] = $count;
            }
            $timeDailyData[] = $item;
        }
        $timeDailyDays = array_keys($timeDaily);
        return $this->success([
            'monthName' => $monthName,
            'global' => [
                'user' => [
                    'total' => $userCount
                ],
                'times' => [
                    'total' => $useTimes
                ],
                'time' => [
                    'total' => $useTime
                ],
                'amount' => [
                    'total' => $amount
                ]
            ],
            'group' => [
                'times' => $timesGroupData,
                'time' => $timeGroupData
            ],
            'goods' => [
                'times' => [
                    'days' => $timesDailyDays,
                    'goods' => $timesDailyGoodsNames,
                    'data' => $timesDailyData
                ],
                'time' => [
                    'days' => $timeDailyDays,
                    'goods' => $timeDailyGoodsNames,
                    'data' => $timeDailyData
                ]
            ]
        ]);
    }
}